q<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset('queryForm')"
            v-if="role != 1"
        >
            <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="90px">
                <el-row :gutter="24" style="height: 50px;">
                    <el-col :span="6" v-if="showDepartment">
                        <el-form-item :label="$t('culture.cultureScheme.proDept')+':'">
                            <el-select
                                v-model="queryForm.projId"
                                style="width: 100%"
                                @change="handleSearch"
                            >
                                <el-option
                                    v-for="item in options.project"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.grade')" prop="grade"
                        >
                            <el-date-picker
                                v-model="queryForm.grade"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                                @change="(queryForm.projId=='1') ? changeFaculty(queryForm.faculty) : ''"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.trainingLevel')" prop="trainingLevel">
                            <DictSelect
                                v-model="queryForm.trainingLevel"
                                @change="changeTrainingLevel"
                                :data="options.trainingLevel"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="queryForm.projId == '1'">
                        <el-form-item filterable :label="$t('culture.profession.category')" prop="professionCateGory">
                            <el-select
                                v-model="queryForm.professionCateGory"
                                @change="changeCategory"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in options.professionCateGory"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.college')" prop="faculty" >
                            <DictSelect
                                filterable
                                @change="changeFaculty"
                                v-model="queryForm.faculty"
                                :data="options.faculty"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <template v-if="queryForm.projId == '1'">
                        <el-col :span="6">
                            <el-form-item filterable label="校内专业:" prop="campusProfession">
                                <el-select v-model="queryForm.campusProfession" style="width: 100%">
                                    <el-option
                                        v-for="item in options.campusProfessions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-else>
                        <el-col :span="6">
                            <el-form-item filterable label="专业:" prop="major">
                                <el-select v-model="queryForm.major" style="width: 100%">
                                    <el-option
                                        v-for="item in options.major"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="学习形式:" prop="formLearning">
                                <el-select v-model="queryForm.formLearning" style="width: 100%">
                                    <el-option
                                        v-for="item in options.formLearning"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="培养类别:" prop="trainingCategory">
                                <el-select v-model="queryForm.trainingCategory" style="width: 100%"
                                clearable multiple collapse-tags>
                                    <el-option
                                        v-for="item in options.trainingCategory"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col :span="6">
                        <el-form-item label="审核状态:" prop="status">
                            <el-select 
                                v-model="queryForm.status" 
                                style="width: 100%" 
                                clearable
                                :disabled="global.isAnyTeacher"
                            >
                                <el-option
                                    v-for="item in options.status"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">{{ $t('message.cultureScheme') }}</h1>
            <div class="div-main clearfix">   
                <div class="float-left">
                    <el-input
                        v-model="queryForm.name"
                        :placeholder="$t('culture.profession.searchForScheneName')"
                        prefix-icon="el-icon-search"
                        @change="handSearchChang"
                    />
                </div>
                <div class="float-right">
                    <el-button @click="advancedExport">
                        高级导出
                    </el-button>
                    <el-button
                        @click="exportFile('word')"
                        v-if="(role == 4 || role == 3) && showOperateButton"
                    >{{ $t('culture.cultureScheme.exportWordZip') }}</el-button>
                    <el-button
                        @click="exportFile('pdf')"
                        v-if="showOperateButton"
                    >{{ $t('culture.cultureScheme.exportPdf') }}</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                stripe
                style="width: 100%"
                @select="selectRow"
                @selection-change="selectionChange"
                tooltip-effect="light"
            >
                <!-- <el-table-column type="expand">
                    <template slot-scope="props">
                        <div class="edu-auto-row">
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">方案名称+++：</div>
                                <div class="edu-auto-content">{{ props.row.name }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">年级：</div>
                                <div class="edu-auto-content">{{ props.row.grade }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">培养层次：</div>
                                <div class="edu-auto-content">{{ props.row.trainingLevelI18n }}</div>
                            </div>
                            <div class="edu-auto-col col" v-if="queryForm.projId == '1'">
                                <div class="edu-auto-label">类别：</div>
                                <div
                                    class="edu-auto-content"
                                >{{ props.row.professionCateGory == "1"? "专业大类": "专业" }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">学院：</div>
                                <div class="edu-auto-content">{{ props.row.facultyI18n }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">专业：</div>
                                <div class="edu-auto-content">
                                    <span>{{ props.row.campusProfessionName}}</span>
                                </div>
                            </div>
                            <div class="edu-auto-col col">
                                <div
                                    class="edu-auto-label"
                                >{{$t('culture.cultureScheme.cultureSchemeStatus')}}:</div>
                                <div class="edu-auto-content">
                                    <el-tag
                                        type="success"
                                        size="mini"
                                        disable-transitions
                                    >{{ getPushLable(props.row.status) }}</el-tag>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column> -->
                <el-table-column type="selection" width="55"/>
                <el-table-column label="方案名称" prop="name">
                    <template slot-scope="scope">
                        <el-tooltip :content="scope.row.name" placement="bottom" effect="light">
                            <el-button
                                type="text"
                                @click="preview(scope.row)"
                            >{{ scope.row.name }}</el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
                 <el-table-column label="年级" prop="grade" width="80"/>
                <el-table-column label="学院" prop="facultyI18n" show-overflow-tooltip/>
                <el-table-column label="专业代码" prop="campusProfession" width="90" />
                <template v-if="queryForm.projId == '1'">
                    <el-table-column label="专业" prop="campusProfessionName" show-overflow-tooltip/>
                </template>
                 <el-table-column label="培养层次" width="80" prop="trainingLevelI18n"/>
               
                    <el-table-column label="类别" width="100">
                        <template
                            slot-scope="scope"
                        >{{scope.row.professionCateGory=="1"? "专业大类": "专业"}}</template>
                    </el-table-column>
                <el-table-column label="下一级审核" prop="approvorName" width="105" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.cultureScheme.cultureSchemeStatus')" width="80">
                    <!-- <template slot-scope="props">
                        <el-tag
                            type="success"
                            size="mini"
                            disable-transitions
                        >{{ getPushLable(props.row.status) }}</el-tag>
                    </template> -->
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 3" type="success" size="mini">
                            通过
                        </el-tag>
                        <el-tag v-if="scope.row.status == 1" type="info" size="mini">草稿</el-tag>
                        <el-tag v-if="scope.row.status == 2" type="warning" size="mini">
                            审核中
                        </el-tag>
                        <el-tag v-if="scope.row.status == 5" type="danger" size="mini">
                            变更中
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryForm.pageSize_"
                        :total="queryForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        style="float: right;margin:0;"
                    />
                </div>
            </div>
            <el-dialog
                :visible.sync="showAdvanceExport"
                title="高级导出"
                width="35%"
                height="50%"
            >
                <div style="width: 80%;margin: 0 auto">
                    <el-form label-width="200" class="demo-dynamic">
                        <el-form-item label="学期" required>
                            <el-select placeholder="请选择学期" v-model="advanceInfo.semester" style="width: 75%">
                                <el-option
                                    v-for="item in options.semester"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeDialog()">取 消</el-button>
                    <el-button type="primary" @click="saveConfirm()">导出</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
import bus from "common/src/utils/bus";
import UTILS from "common/src/utils/utils";
import {judgeManagement} from '../culturescheme/common';
import { queryDic, findTrainingLevelByProjId, advanceExport } from "common/src/api/dictionary";
import { findFaculty } from "common/src/api/faculty";
import { findProfessionByParam,
findCultureSchemeById,
exportCultureSchemePdfOrWordZip,
findCultureSchemeListForMange,
getSchemeSchoolTerm,
getPower } from 'common/src/api/culture/bachelor';
// import { getGraduateDegreePage } from "common/src/api/resource/course";
import mixin from 'common/src/mixins/index';
export default {
    name: "bclQueryCultureScheme",
    mixins: [mixin],
    data() {
        return {
            isGraduate: true,
            showAdvanceExport: false,
            // 筛选相关选项
            queryForm: {
                "x-token": "",
                grade: "", // 年级
                trainingLevel: "", // 培养层次
                faculty: "", // 学院
                projId: "1", //	部门管理
                professionCateGory: "", //专业类别(1 专业大类 2 专业),
                campusProfession: "", //	本科生专业
                major: "", // 研究生专业
                type: "", // pdf或者word
                status: "", // 状态 选项通过审批的培养方案
                formLearning: "", // 学习形式
                trainingCategory: [], //培养类别
                name: "", // 名称
                degreeType: "",  // 学位类型
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },
            advanceInfo: {
                semester: '',
                id: ''
            },
            // 下拉相关选项数据
            options: {
                project: [],
                trainingLevel: [],
                professionCateGory: [],
                faculty: [],
                major: [],
                semester: [],
                formLearning: [],
                trainingCategory: [], // 培养类别,
                professionCateGory: [
                    { value: "", label: this.$t("message.all") },
                    {
                        value: "1",
                        label: this.$t("culture.profession.bigProfession")
                    },
                    {
                        value: "2",
                        label: this.$t("culture.profession.profession")
                    }
                ],
                campusProfessions: [],
                currentRole: '',
                status: [
                    {
                        label: '通过',
                        value: 3
                    },
                    {
                        label: '草稿',
                        value: 1
                    },
                    {
                        label: '审核中',
                        value: 2
                    },
                    {
                        label: '变更中',
                        value: 5
                    }
                ],
                degreeType: []
            },
            tableData: [],
            role:'',
            showDepartment: false
        };
    },

    created() {
        if(this.global.isAnyTeacher){
            this.queryForm.status = 3
        }
        this.init();
        this.getRole();
        this.initProjId();
        this.setExportButtonVisible();
        this.initCurrentRole();
        // bus.$on("updateCurrentManageDeptId", id => {
        //     this.queryForm.projId = id;
        //     this.initTrainingLevelOptions();
        //     this.handleSearch();
        // });
    },
    methods: {
        initSemesterListMap() {
            getSchemeSchoolTerm(this.advanceInfo.id).then(res => {
                if (res.code == 200) {
                    let schoolTerm = 0
                    schoolTerm = res.data.schoolTerm 
                    let list = [];
                    let labelArr = ['一',  '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'];
                    for(let i = 0 ; i< schoolTerm; i++) {
                        list.push({
                            label: labelArr[i],
                            checked: false,
                            key: i + 1,
                            value: i + 1
                        })
                    }
                    this.options.semester = list;
                }
                
            })
        },
        initProjId() {
            let currentUser =this.global.currentUser;
            if(currentUser.currentRole == 1) {
                //this.queryForm.projId = currentUser.currentManageDptId;
                this.initTrainingLevelOptions()
                this.handleSearch()
            } else {
                this.initProjs();
            }
            this.currentRole = currentUser.currentRole;
        },
        getRole(){
            getPower().then((res) => {
                this.role = res.data.power;
            })
        },
        initCurrentRole() {
            // let currentUser =this.global.currentUser;
            // this.showDepartment = currentUser.currentRole == "2"  && judgeManagement.call(this,this.$route.path).length>1;
        },
        initTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    //this.queryForm.trainingLevel = "";
                    this.options.trainingLevel = res.data;
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = [];
            this.options[optionKey] = dataObj.map(item => ({
                label:
                    "en" === this.$store.getters.language
                        ? item.nameEN
                        : item.nameCN,
                value: item.code
            }));
        },
        setExportButtonVisible() {
            let currentUser =
                this.$store.state.session.user ||
                JSON.parse(localStorage.getItem("user"));
            this.showOperateButton = currentUser.currentRole == 1;
        },
        preview(row) {
            this.$router.push({
                path: "/bclCultureTemplateView",
                query: {
                    projId: this.queryForm.projId,
                    id: row.id,
                    dataType: 2
                }
            });
        },
        init() {
            this.queryForm["x-token"] =
                this.$store.state.session.sessionid ||
                localStorage.getItem("sessionid") ||
                "";
            // for(var i = 1; i < 13; i++){
            //     this.options.semester.push({
            //         key: i,
            //         label: i,
            //         value: i
            //     })
            // }
            this.initOptions();
        },
        async initProjs(){
            let params = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_GLBM"]
            };
            let res = await queryDic(params);
            let user = this.$store.state.session.user || JSON.parse(localStorage.getItem('user'));
            let {manageDptIds} = user;
            let {code, data: {X_GLBM}} = res;
            if (code === 200) {
                let dpts = Object.keys(X_GLBM).map(item => ({
                    label: X_GLBM[item],
                    value: item + ""
                }))
                this.options.project = (manageDptIds && manageDptIds instanceof Array && manageDptIds.length >0) ? dpts.filter(item => {
                    return manageDptIds.indexOf(item.value) > -1;
                }) : [];
            }
            //this.queryForm.projId = this.options.project[0].value;
            this.initTrainingLevelOptions()
            this.handleSearch()
        },
        initOptions() {
            findFaculty().then(res => { 
                let data = {"X_YX": res.data};
                UTILS.fillSelect({ faculty: "X_YX" }, data, this.options);
            });
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_PYCC", "X_PYLB", "X_XXXS", "X_XWLX"]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            trainingLevel: "X_PYCC",
                            formLearning: "X_XXXS",
                            trainingCategory: "X_PYLB",
                            degreeType: "X_XWLX"
                        },
                        res.data,
                        this.options
                    );
                }
            });
        },
        handleSearch() {
            this.getCultureSchemes();
        },
        async getCultureSchemes() {
            await this.initTrainingLevelOptions();
            findCultureSchemeListForMange(this.queryForm).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list;
                    this.queryForm.pageNum_ = res.data.pageNum_;
                    this.queryForm.pageSize_ = res.data.pageSize_;
                    this.queryForm.total = res.data.total_;
                }
            });
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getCultureSchemes();
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getCultureSchemes();
        },
        handSearchChang() {
            this.getCultureSchemes();
        },
        selectionChange(selection) {
            const self = this;
            self.multipleSelection = selection;
        },
        changeFaculty(val) {
            const self = this;
            if (self.queryForm.projId == "1") {
                let query = {};
                query.faculty = val;
                query.grade = +self.queryForm.grade;
                query.trainingLevel = self.queryForm.trainingLevel;
                query.category = self.queryForm.professionCateGory;
                self.queryCampusProfessions(query);
            } 
        },
        changeTrainingLevel(val) {
            if (this.queryForm.projId != "1") {
                return;
            }
            const self = this;
            let query = {};
            query.faculty = self.queryForm.faculty;
            query.grade = +self.queryForm.grade;
            query.trainingLevel = val;
            query.category = self.queryForm.professionCateGory;
            self.queryCampusProfessions(query);
        },
        changeCategory(val) {
            const self = this;
            let query = {};
            query.faculty = self.queryForm.faculty;
            query.grade = +self.queryForm.grade;
            query.trainingLevel = self.queryForm.trainingLevel;
            query.category = val;
            self.queryCampusProfessions(query);
        },
        queryCampusProfessions(query) {
             // 联动校验
            if(!(query.faculty)) {
              return
            }
            query.inUsed="0";
            //适配专业那边得接口，为了拿到全量数据 分页给上100（专业那边又不可能配合我）
            query.pageNum_=1
            query.pageSize_=100
            this.options.campusProfessions = [];
            this.queryForm.campusProfession = "";
            findProfessionByParam(query).then(res => {
                if (res.code == 200) {
                    this.options.campusProfessions = res.data.list.map(
                        (item, index) => {
                            return {
                                label: item.professionName + '-' + item.professionCode,
                                value: item.professionCode
                            }
                        }
                    );
                }
            });
        },

        onSubmit() {
            this.getCultureSchemes();
        },
        reset(ref) {
            this.queryForm.name = "";
            if(this.role == 3){
                this.getRole();
                this.$refs[ref].resetFields();
                this.getCultureSchemes();
            }else{
                this.options['major'] = [];
                this.$refs[ref].resetFields();
                this.getCultureSchemes();
            }
            this.queryForm.pageNum_ = 1
            this.queryForm.pageSize_ = 20
        },
        detailCultureScheme(id) {
            getCultureSchemeById(id).then(res => {
                if (res.code == 200) {
                }
            });
        },

        exportFile(type) {
            const ids = _.map(this.multipleSelection, "id");
            if(ids.length==0){
                this.$message({
                    type: "warning",
                    message: "请勾选培养方案再导出数据"
                });
                return; 
            }
            const str = ids.join(",");
            let data={
                ids:str,
                type :type,
                projId:this.queryForm.projId,
                status:this.queryForm.status
            };
            data['x-token']=this.queryForm['x-token'];
            exportCultureSchemePdfOrWordZip(data);
        },
        getPushLable(val) {
            return val ? this.$t("culture.cultureScheme.approval") : "";
        },
        /**
         * 高级导出
         */
        advancedExport() {
            const ids = _.map(this.multipleSelection, 'id')
            if (ids.length === 0) {
                this.$notify.warning({
                    title: '提示',
                    message: '您还没有选择任何方案！'
                })
                return
            } else if (ids.length > 1) {
                this.$notify.warning({
                    title: '提示',
                    message: '只能选择一条数据'
                })
                return
            }
            this.advanceInfo.id = ids[0];
            this.initSemesterListMap();
            this.showAdvanceExport = true;
        },
        saveConfirm() {
            if(!this.advanceInfo.semester){
                 this.$message({
                    type: "warning",
                    message: "请先选择学期再导出数据"
                });
                return; 
            }
            advanceExport(this.advanceInfo.id, this.advanceInfo.semester);
            this.showAdvanceExport = false;
        },
        closeDialog() {
            this.showAdvanceExport = false;
        }
    }
};
</script>
<style lang="scss" scoped>
.div-main {
    margin-bottom: 16px;
  }
</style>

